import {getMyInfoUsingGet, updateAvatarUsingPost} from '@/services/backend/userController';
import {
  GridContent,
  type ProColumns,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Card, Col, Layout, message, Row, Space} from 'antd';
import React, {useEffect, useState} from 'react';
import UpdatePasswordModal from "@/pages/MineInfo/components/UpdatePasswordModal";
import UpdateInfoModal from "@/pages/MineInfo/components/UpdateInfoModal";

/**
 * 用户管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示新建窗口
  // const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  // const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  // const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [userInfoData, setUserInfoData] = useState<API.UserInfoVO>();
  // 是否显示更新窗口
  const [updatePasswordModalVisible, setUpdatePasswordModalVisible] = useState<boolean>(false);
  const [updateInfoModalVisible, setUpdateInfoModalVisible] = useState<boolean>(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  /**
   * 加载个人信息
   */
  const loadData = async () => {
    try {
      const res =  await getMyInfoUsingGet()
      if(res.data){
        setUserInfoData(res.data);
      }
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
  };

  useEffect(() =>{
    loadData();
  },[])

  const handleSelectAvatar = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*'; // 限制只能选择图片
    input.onchange = (e) => {
      // @ts-ignore
      const file = e.target.files[0];
      if (file) {
        setSelectedFile(file);
        // 这里可以直接调用上传函数，或者先显示一个确认对话框
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        handleUploadAvatar(file);
      }
    };
    input.click();
  };
  const handleUploadAvatar = async (file: File) => {
    try {
      const body = {}; // 根据你的API需求，这里可能需要一些额外的用户信息或其他数据
      const response = await updateAvatarUsingPost(body, file);
      if (response.data) {
        message.success('头像上传成功');
        // 成功后可能需要重新加载用户信息
        loadData();
      } else {
        message.error('头像上传失败');
      }
    } catch (error: any) {
      message.error('上传时发生错误: ' + error.message);
    }
  };

  const columns: ProColumns<API.UserUpdatePasswordRequest>[] = [
    {
      title: '新密码',
      dataIndex: 'userPassword',
      valueType: 'password',
    },
    {
      title: '确定新密码',
      dataIndex: 'checkPassword',
      valueType: 'password',
    }
    ];

  const columnsInfo: ProColumns<API.UserUpdateInfoRequest>[] = [
    {
      title: '公众号OpenId',
      dataIndex: 'mpOpenId',
      valueType: 'text',
    },
    {
      title: '微信开放平台id',
      dataIndex: 'unionId',
      valueType: 'text',
    },
    {
      title: '昵称',
      dataIndex: 'userName',
      valueType: 'text',
    },
    {
      title: '手机',
      dataIndex: 'phone',
      valueType: 'text',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      valueType: 'text',
    },
    {
      title: '个人简介',
      dataIndex: 'userProfile',
      valueType: 'textarea',
    }
  ];

  return (
    <GridContent>
      <Row gutter={24}>
        <Col lg={6} md={24}>
          <Layout>
            <Card
              hoverable
              style={{width: 350, marginRight: 10}}
              cover={<img alt="example" src={userInfoData?.userAvatar}/>}
            >
              <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                <Button type={"primary"} onClick={handleSelectAvatar}>
                  修改头像
                </Button>
              </div>
              <div style={{fontSize: 22, color: 'black', textAlign: 'center'}}>
                <img
                    alt=""
                    src={require('@/assets/mine_icon.png')}
                  style={{width: 30, textAlign: 'center'}}
                />
                : {userInfoData?.userName}
              </div>
              <div style={{fontSize: 14, color: 'gray', textAlign: 'left', paddingTop: 10}}>
                简介：{userInfoData?.userProfile}
              </div>
              <br></br>
              <div style={{fontSize: 14, color: 'gray', textAlign: 'left'}}>
                账户：{userInfoData?.userAccount}
                <br></br>
                权限：{userInfoData?.userRole==='admin' ? '管理员': '用户'}
                <br></br>
                手机：{userInfoData?.phone}
                <br></br>
                邮箱：{userInfoData?.email ? userInfoData.email: '暂时未填写'}
                <br></br>
                微信开放平台Id：{userInfoData?.unionId? userInfoData.unionId: '暂时未填写'}
                <br></br>
                公众号OpenId：{userInfoData?.mpOpenId? userInfoData.mpOpenId: '暂时未填写'}
              </div>
                <br></br>
                <div style={{fontSize: 14, color: 'gray', textAlign: 'left'}}>
                  加入日期：
                  {userInfoData?.createTime
                    ? userInfoData.createTime.substring(0, 10)
                    : '？？？'}
                  <br></br>
                  更新日期：
                  {userInfoData?.updateTime
                    ? userInfoData.updateTime.substring(0, 10)
                    : '？？？'}
                </div>
                {/*todo 修改个人信息，修改密码*/}
                <Space style={{marginTop: 20 ,display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                  <Button
                    type="primary"
                    onClick={() => {
                      setUpdateInfoModalVisible(true);
                    }}
                  >
                    修改基础信息
                  </Button>
                  <Button
                    type="primary"
                    danger
                    onClick= {() => {
                      setUpdatePasswordModalVisible(true);
                    }}
                  >
                    修改密码
                  </Button>
                </Space>
            </Card>
          </Layout>
        </Col>
        <Col lg={17} md={24}>
          {/*todo 更改卡片为个人其余信息，如个人发布文章、关注的用户、个人收藏的文章等*/}
          <Card hoverable cover={<img alt="example" src={require('@/assets/404_logo.png')} />}>
          </Card>

          <UpdatePasswordModal
              visible={updatePasswordModalVisible}
              columns={columns}
              onSubmit={() => {
                setUpdatePasswordModalVisible(false);
              }}
              onCancel={() => {
                setUpdatePasswordModalVisible(false);
              }}
          />
          <UpdateInfoModal
              visible={updateInfoModalVisible}
              columns={columnsInfo}
              oldData={userInfoData}
              onSubmit={() => {
                setUpdateInfoModalVisible(false);
                loadData();
              }}
              onCancel={() => {
                setUpdateInfoModalVisible(false);
              }}
          />
        </Col>
      </Row>

    </GridContent>
  );
};
export default UserAdminPage;
